from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.core.paginator import Paginator
from django.db.models import Max, Q, F, Min, Avg, Count, Sum
from django.contrib.auth.hashers import make_password, check_password
import datetime  # 导入时间包
import time
import random
from utils.comm import send_message
from utils.comm import get_redis_conn
from .ser import *
from django.http import HttpResponse
from MeiDuo import settings


# Create your views here.


# 测试
class Text(APIView):
    def get(self, request):
        # coom = redis.Redis('localhost', port=6379) #换成分装方法代替
        coom = get_redis_conn()
        coom.setex('username', 5, '小米')  # 5秒后消失需要注释这行 不然刷新一直有这行
        name = coom.get('username')
        return Response(name)


# 添加新闻
class MNewmanage(APIView):
    def post(self, request):
        ser = MNewSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 20010})

    def get(self, request):
        cpage = request.GET.get('cpage')
        if cpage:
            new = MNew.objects.all()
            news = Paginator(new, 2)
            new_cpage = news.page(cpage)
            ser = MNewSer(new_cpage, many=True)
            tpage = news.num_pages
            return Response({"code": 200, 'list': ser.data, 'tpage': tpage})
        else:
            new = MNew.objects.all()
            ser = MNewSer(new, many=True)
            return Response({"code": 200, 'list': ser.data})


# 添加广告
class Madvertisingmanage(APIView):
    def post(self, request):
        ser = MadvertisingmanageSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 20010})

    def get(self, request):
        cpage = request.GET.get('cpage')
        if cpage:
            advertising = Madvertising.objects.all()
            advertisings = Paginator(advertising, 2)
            advertisings_cpage = advertisings.page(cpage)
            ser = MadvertisingmanageSer(advertisings_cpage, many=True)
            tpage = advertisings.num_pages
            return Response({"code": 200, 'list': ser.data, 'tpage': tpage})
        else:
            advertising = Madvertising.objects.all()
            ser = MadvertisingmanageSer(advertising, many=True)
            return Response({"code": 200, 'list': ser.data})


# 友情链接
class Friendlink(APIView):
    def post(self, request):
        link = request.GET.get('link')
        ser = MadvertisingmanageSer(data=request.data)
        if ser.is_valid():
            ser.save()
            # addlink = Madvertising.objects.all(id=link).frist()
            # addlink.count +=1
            # addlink.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 20010})


# 美多 开始
import re


# 注册页面
class Registermanage(APIView):
    def post(self, request):
        # 验证用户名
        # 获取用户名
        username = request.data.get('username')
        # 用户名是否为空
        if not username:
            return Response({'code': 10010})
        # 用户名是否符合规则 正则
        if not re.match('^\w{5,10}$', username):
            return Response({'code': 10011})
        # 用户名是否唯一
        user = User.objects.filter(username=username).first()
        if user:
            return Response({'code': 10012})
        # 验证密码
        # 获取密码
        password = request.data.get('password')
        # 密码是否为空
        if not password:
            return Response({'code': 10016})
        # 密码是否符合规则 正则
        if not re.match('^[a-zA-Z0-9]{8,20}$', password):
            return Response({'code': 10017})
        # 密码是否注册
        pas = User.objects.filter(password=password).first()
        if pas:
            return Response({'code': 10018})

        # 确认密码
        conpassword = request.data.get('conpassword')
        print(conpassword)
        if conpassword == password:
            return Response({'code': 10019})
        else:
            return Response({"code": 10020})

        # 验证手机号
        # 获取手机号
        mobile = request.data.get('mobile')
        # 手机号是否为空
        if not mobile:
            return Response({'code': 10013})
        # 手机号是否符合规则 正则
        if not re.match('^1[3-9]\d{9}$', mobile):
            return Response({'code': 10014})
        # 手机号是否注册
        mob = User.objects.filter(mobile=mobile).first()
        if mob:
            return Response({'code': 10015})

        # 验证收到的手机验证码
        veri = request.data.get('veri')
        coom = get_redis_conn()
        mo = coom.get(mobile)
        if mo:
            mo = str(mo, encoding='utf8')
            if veri == mo:
                return Response({"code": 10021})

        return Response({'code': 200})


import redis


# 发送短信
class SendManage(APIView):
    def post(self, request):
        # 获取号码
        mobile = request.data.get('mobile')
        # 获取uid
        uid = request.data.get('uid')
        # 获取图形验证码
        uuidurl = request.data.get('uuidurl')
        # 开启reids 获取uid的值
        coom = get_redis_conn()
        imguid = coom.get(uid)  # 取出图形验证码
        if imguid:
            imguid = str(imguid, encoding='utf8')
            if uuidurl.lower() == imguid.lower():
                num = random.randint(1000, 9999)
                res = send_message(mobile, str(num), 1)
                print(res)
                code = 10010
                if res:
                    code = 200
                    # 发送验证码后存入redis

                    coom = get_redis_conn()
                    coom.setex(mobile, 60, num)
                    return Response({'code': code})
        return Response({'code': 20010})


from utils.captcha.captcha import captcha


# 获取图片验证码
class CreatCaptcha(APIView):
    def get(self, request):
        # 导用cpatcha  text是图片验证码中数字 img是字节流
        name, text, img = captcha.generate_captcha()
        # 开启redis
        coom = get_redis_conn()
        # 获取图片验证码 uuid
        uuid = request.GET.get('uid')
        # print(uid)
        # print(text)
        # 保存图形验码
        coom.set(uuid, text)  # set中前一个参数是键 后一个参数是值
        return HttpResponse(img, content_type='image/jpg')

    # 注册按钮提交数据
    def post(self, request):
        username = request.data.get("username")
        request.data['password'] = make_password(request.data.get('password'))
        ser = CreatCaptchaSer(data=request.data)
        if ser.is_valid():
            ser.save()
            user = User.objects.filter(username=username).first()
            # 生成token
            import jwt
            token = jwt.encode({'data': {'username': username}}, settings.SECRET_KEY, algorithm='HS256')
            return Response({'code': 200, "token": token, "userid": user.id})
        return Response({'code': 20010})


class LoginAPI(APIView):
    def post(self, request):
        username = request.data.get("username")
        password = request.data.get("password")
        user = User.objects.filter(username=username).first()
        if user:
            if check_password(password, user.password):
                import jwt
                token = jwt.encode({'data': {'username': username}}, settings.SECRET_KEY, algorithm='HS256')
                return Response({"code": 200, "token": token, "userid": user.id})
        return Response({"code": 20022})


class addAPI(APIView):
    def post(self, request):
        ser = AddressSer(data=request.data)
        if ser.is_valid():
            ser.save()
            return Response({"code": 200})
        else:
            print(ser.errors)
            return Response({"code": 12345})


class AreaM(APIView):
    def get(self, request):
        pid = request.GET.get('pid')
        if not pid:
            # 获取省
            areas = Area.objects.filter(parent_id__isnull=True).all()
        else:
            # 获取市或者区
            areas = Area.objects.filter(parent_id=pid).all()

        ser = AreaSer(areas, many=True)
        return Response({"code": 200, 'list': ser.data})


class AddressAPI(APIView):
    def get(self, request):
        uid = request.GET.get("uid")
        addr = Address.objects.filter(user_id=uid).all()
        ser = ShowAddressSer(addr, many=True)
        return Response({"code": 200, "list": ser.data})

    def put(self, request):
        # 获取要设置默认得ID
        id = request.GET.get('id')
        # 通过ID获取数据
        address = Address.objects.filter(id=id).first()
        # 把之前默认的地址改为普通的
        Address.objects.filter(user_id=address.user_id, is_default=1).update(is_default=0)
        # 把要操作的设置为默认
        address.is_default = 1
        # 保存
        address.save()
        return Response({'code': 200})
